package com.kime.email.spring.controller;

import com.kime.email.spring.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping()
public class IndexController {

    @Autowired
    private MailService mailService;

    @Autowired
    private TemplateEngine templateEngine;

    @RequestMapping("/index")
    public String index(Model model) {
        return "emailTemplate.html";
    }

    @RequestMapping("/template")
    @ResponseBody
    public Map<String, Object> sendTemplateEmail(@RequestParam String to, @RequestParam String subject) {
        Context context = new Context();
        context.setVariable("name", to);
        String emailContent = templateEngine.process("emailTemplate", context);
        boolean flag = mailService.sendTemplateEmail(to, subject, emailContent);
        if (flag) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", 200);
            map.put("message", "success");
            return map;
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("code", 100);
            map.put("message", "fail");
            return map;
        }
    }
}
